import asyncio
import logging

from openpyxl.workbook import Workbook

from crawler.page.base_page import BaseCrawlerPage

LOGGER = logging.getLogger(__name__)


class PSPage(BaseCrawlerPage):
    # 菜单栏选择器
    menu_selector = 'xpath=//*[@id="app"]/section/main/section/aside/div/ul'
    # 工单中心菜单选择器
    work_order_center_selector = f'{menu_selector}//*[@class="ant-menu-submenu-title"][.//*[text()="工单中心"]]'
    # 工单中心菜单判断是否展开属性 true 展开 false 未展开
    aria_expanded = 'aria-expanded'
    # ps工单管理面选择器
    ps_work_order_selector = f'{menu_selector}//*[text()="PS工单管理"]'
    # 页面搜索框选择器
    # 创建时间-日期开始
    create_time_start_selector = 'xpath=//*[@id="query_date"]'
    # 创建时间-日期结束
    create_time_end_selector = 'xpath=//*[@id="waterCanves"]/div[1]/div/form/div/div[7]/div/div[2]/div/div/div/div[3]/input'
    # 搜索按钮选择器
    search_button_selector = 'xpath=//*[@id="waterCanves"]/div[2]/div/div/div/button[1]'
    # 表格数据选择器
    table_selector = '.ag-center-cols-container'
    # 下一页按钮选择器
    next_button_selector = '.ant-pagination-next > .ant-pagination-item-link'

    columns = {
        "工单日期": 'appDate',
        "工单单号": 'workId',
        "客户姓名": 'custName',
        "案件编号": 'sysRecordkey',
        "工单内容": 'workNotes',
        "工单处理人": 'dealCollectorText',
        "客户手机号": 'mobile',
        "工单状态": 'workStatus',
        "处理结果": 'dealNotes',
        "进线次数": 'incomingFrequency',
        "来电手机号": 'phone'
    }

    async def data_write_excel(self, search, file_path):
        """
        工单页面数据写入 Excel 文件

        :param file_path: 数据保存文件路径
        :param search: 搜索参数
        :return: 分页表格数据
        """
        # 数据写入
        # 创建一个新的工作簿
        wb = Workbook()
        # 获取活动工作表
        ws = wb.active

        start_date = search.get("start_date")
        end_date = search.get("end_date")
        if not start_date and not end_date:
            LOGGER.error("查询参数有误,无法查询")
            raise ValueError("查询参数有误,无法查询")

        LOGGER.info("入参: start_date=%s, end_date=%s", start_date, end_date)
        title_data = list(self.columns.keys())
        ws.append(title_data)
        self._save_workbook(wb, file_path)

        try:
            LOGGER.info("开始获取工单页面数据")
            menu_element = await self._get_element(self.menu_selector, "菜单栏")
            if menu_element:
                work_order_center_element = await self._get_element(self.work_order_center_selector, "工单中心菜单")
                if work_order_center_element:
                    await self._expand_menu(work_order_center_element, self.aria_expanded)
                    await asyncio.sleep(0.3)
                    ps_work_order_element = await self._get_element(self.ps_work_order_selector, "ps工单管理面")
                    if ps_work_order_element:
                        await self._click_element(ps_work_order_element, "ps工单管理面")
                        await self._set_date_range(start_date, end_date)
                        await self._click_search_button(self.search_button_selector)
                        await self._parse_table_data(ws, file_path, wb, self.columns)
        except Exception as e:
            # 抛出
            LOGGER.error("获取工单页面数据时出错: %s", str(e), exc_info=True)
            raise
        finally:
            self._save_workbook(wb, file_path)
            await self.page.reload()
